package com.secret.manager.service.impl;

import com.secret.core.constant.ServiceConstant;
import com.secret.dao.dto.PictureDownloadDto;
import com.secret.dao.entity.UserControls;
import com.secret.dao.mapper.UserControlsMapper;
import com.secret.dao.mapper.UserLoginMapper;
import com.secret.manager.aes.MyAESUtil;
import com.secret.manager.redis.RedisUtils;
import com.secret.manager.service.TransactionConsistency;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@Service
public class TransactionConsistencyImpl implements TransactionConsistency {
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private UserControlsMapper userControlsMapper;
    @Resource
    private UserLoginMapper userLoginMapper;
    @Resource
    private UserControls userControls;
    @Resource
    private MyAESUtil myAESUtil;

    @Override
    @Transactional
    /**
    redis相关内容还需要设置过期时间定时执行
    **/
    public int selectCount(String key) {
        Long size=redisUtils.lGetListSize(key);
        int b=size.intValue();
        if (b>=ServiceConstant.MAX_USER_CONTROLS){
            List<Object> list=redisUtils.lGet("userControls",0,-1);
            List<UserControls> DBList=new ArrayList<UserControls>();
            for (Object o:list){
                /*对象转换*/
                DBList.add(userControls.getClass().cast(o));
            }
            return userControlsMapper.insertUserControlsList(DBList);
        }
        return 0;
    }

    @Override
    @Transactional
    public int insertWangBi(String userOpenId,int count) {
        return userLoginMapper.updateCountByOpenId(userOpenId,count);
    }


    @Override
    public List<PictureDownloadDto> AESList(List<PictureDownloadDto> pictureList, String key, String type)  throws Exception {
        if (type.equals("E")){
            for (PictureDownloadDto pictureDownloadDto1 : pictureList) {
                pictureDownloadDto1.setPictureName(myAESUtil.Encrypt(pictureDownloadDto1.getPictureName(),key));
                pictureDownloadDto1.setPictureUrl(myAESUtil.Encrypt(pictureDownloadDto1.getPictureUrl(),key));
            }
            return pictureList;
        }else {
            for (PictureDownloadDto pictureDownloadDto1 : pictureList) {
                pictureDownloadDto1.setPictureName(myAESUtil.Decrypt(pictureDownloadDto1.getPictureName(),key));
                pictureDownloadDto1.setPictureUrl(myAESUtil.Decrypt(pictureDownloadDto1.getPictureUrl(),key));
            }
            return pictureList;
        }

    }
}
